<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="880px"
  >
    <BasicTable
      @register="registerUsersTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="usersData.users"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, inject, provide } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { getRoleUsers, setRoleUsers } from '/@/api/project/role';
  import { roleUsersTableColumns } from './role.data';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetRoleUsers',
    components: {
      BasicModal,
      BasicTable,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const op = ref(OperationTypeEnum.UN_KNOWN);
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const moduleName = inject<string>('moduleName');
      const tableTitle = ref('人员列表');

      const dataId = ref('');

      //勾选的用户id集合
      const uids = ref<number[] | string[]>([]);

      //处理过后的table数据
      const usersData = reactive({
        checkedKeys: [],
        users: [],
      });

      const [registerUsersTable, { setSelectedRowKeys, getSelectRowKeys, clearSelectedRowKeys }] =
        useTable({
          title: tableTitle,
          // api: getProjectUsers,
          columns: roleUsersTableColumns, //表头数据
          showTableSetting: true, //是否显示表格设置
          bordered: true,
          showIndexColumn: true,
          pagination: true, //关闭分页
          rowSelection: { type: 'checkbox' },
          rowKey: 'id',
          clickToRowSelect: false,
        });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId; //角色id
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        getUsers();

        //后台返回的数据如果有已经关联的则设置选中行
        setSelectedRowKeys(usersData.checkedKeys);
      });

      /**
       * 获取人员列表
       */
      async function getUsers() {
        //每次打开窗口都会重复加载数据，在加载数据前如果有数据先清空
        if (usersData.users.length > 0) {
          usersData.users = [];
          usersData.checkedKeys = [];
        }
        //调用后端接口获取数据
        getRoleUsers(dataId.value)
          .then((res) => {
            console.log('res', res);
            //处理返回数据
            res.forEach((val) => {
              usersData.users.push(val.user);
              //获取设置部门之前已经关联的部门id，用于回显勾选
              if (val.checked === true) {
                usersData.checkedKeys.push(val.user.id);
              }
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        //获取设置选中的用户id集合
        uids.value = getSelectRowKeys();
        try {
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          setRoleUsers({ roleid: dataId.value, uids: uids.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('设置成功', 2);
              }
              closeModal();
              emit('success');
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }

        // 清空选中的行;
        clearSelectedRowKeys();
      }

      return {
        op,
        moduleName,
        modalTitle,
        // UsersModuleName,
        registerModal,
        registerUsersTable,
        getUsers,

        usersData,
        onButtonOkClick,
      };
    },
  });
</script>
